'use strict';
const moment = require('moment');
const async = require('async');
const superagent = require('superagent');
const yjxUserUtil = require('../../yjx/v1/util/userUtil');
const YjxUserModel = require('../../../common/yjxMysql/mapping/YjxUserModel');
const YjxThirdPartyUserModel = require('../../../common/yjxMysql/mapping/YjxThirdPartyUserModel');
const YjxOrgRModel = require('../../../common/yjxMysql/mapping/YjxOrgRModel');
const YjxActUserReward = require('../../../common/yjxMysql/mapping/YjxActUserReward');
const YjxCouponModel = require('../../../common/yjxMysql/mapping/YjxCouponModel');
const codeUtil = require('../commonUtils/codeUtil');
const assetUtil = require('../commonUtils/assetUtil');


// 默认用户头像
const DEFAULT_USER_PROFILE_PHOTO = "http://itbour-back.oss-cn-hangzhou.aliyuncs.com/image/U13396/2017/12/15/181805976_wapZT7TnmRu3VV3Sm1MY";
// 默认用户签名
const DEFAULT_USER_SIGNATURE = "放纵你的自由";

const userCenterServiceUtil = (function () {

    function userCenterServiceUtil() {

    }

    /**
     * 获取用户信息
     *
     * @author 王俊
     * @date 2017-07-18
     *
     * @param {Object} option 请求参数
     * @param {Number} option.device            设备标识
     * @param {Number} option.userId            用户唯一标识
     * @param {Number} option.withOrganization  是否获取用户组织信息
     * @param {String} option.withReward        是否获取用户收益信息
     * @param {Number} option.withWallet        是否获取用户秀米钱包信息
     *
     * @param {Function} callback 回调函数
     *                      错误原因
     */
    userCenterServiceUtil.getUserInfo = function (option, callback) {
        const totalTasks = [];

        // 1. 获取基础信息
        totalTasks.push(function (callback) {
            userCenterServiceUtil.getUserProfileInfo(option, function (error, userInfo) {
                const data = {};
                data.retData = userInfo;
                return callback(error, data);
            });
        });
        // 2. 按需获取用户组织信息
        if(option.withOrganization) {
            totalTasks.push(function (data, callback) {
                userCenterServiceUtil.getUserOrganizationsInfo(option, function (error, organizations) {
                    data.retData.userInfo.organizations = organizations;
                    return callback(error, data);
                });
            });
        }

        // 3. 按需获取收益信息
        if(option.withReward) {
            totalTasks.push(function (data, callback) {
                userCenterServiceUtil.getUserRewardInfo(option, function (error, reward) {
                    data.retData.userInfo.reward = reward;
                    return callback(error, data);
                })
            });
        }

        // 4. 按需获取秀米包信息
        if(option.withWallet) {
            totalTasks.push(function (data, callback) {
                userCenterServiceUtil.getUserXMWalletInfo(option, function (error, wallet) {
                    data.retData.userInfo.wallet = wallet;
                    return callback(error, data);
                });
            });
        }

        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error);
            return callback(error, data.retData);
        });
    };




    /**
     * 获取用户的基础信息
     *
     * @author 王俊
     * @date 2017-07-18
     *
     * @param {Object} option
     * @param {Number} option.userId
     * @param {Function} callback 回调函数
     *                      错误原因
     */
    userCenterServiceUtil.getUserProfileInfo = function (option, callback) {

        const totalTasks = [];

        // 1. 获取用户基本信息
        totalTasks.push(function (callback) {
            const entity =  new YjxUserModel({
                user_id: option.userId
            });
            //查询用户信息
            entity.findFromDB(function(error, users){
                if (error || !users || users.length <=0) {
                    return callback(error || '该用户不存在', null);
                }
                const data = {};
                data.userEntity = users[0];
                return callback(error, data);
            });
        });
        // 2. 获取用户第三方信息
        totalTasks.push(function (data, callback) {
            const entity =  new YjxUserModel({
                user_id: option.userId
            });
            entity.getThirdPartyUserInfo(option.userId, function (error, thirdParts) {
                if(error || !thirdParts || thirdParts.length <=0) {
                    return callback(error || '该用户不存在', null);
                }
                data.thirdParts = thirdParts;
                return callback(error, data);
            });
        });
        // 3. 重组用户信息
        totalTasks.push(function (data, calback) {
            data.retData = {};
            data.retData.mobile = {};
            data.retData.wechat = {};
            data.retData.QQ = {};
            data.retData.sinaWeibo = {};

            // 重组用户信息
            data.retData.userInfo = {
                userId : data.userEntity.user_id,
                evaluation:data.userEntity.evaluation, // 用户评价分, 默认为0
                nickName : data.userEntity.nickname || "",
                avatarUrl : data.userEntity.profile_photo || DEFAULT_USER_PROFILE_PHOTO,
                sign : data.userEntity.signature || DEFAULT_USER_SIGNATURE
            };

            // 重组三方平台信息
            for (let i = 0; i < data.thirdParts.length; i++) {
                const tp = data.thirdParts[i];
                //手机号
                if (tp.account_type === 10) {
                    data.retData.mobile = {
                        zone: tp.field2 || "",
                        mobile: tp.field1 || ""
                    }
                }
                // 微信用户
                else if (tp.account_type === 20) {
                    data.retData.wechat = {
                        union: tp.field1 || "",       // 微信 unionId
                        token: tp.field2 || "",       // 微信 openId
                        nickName: tp.nickname || "",
                        avatarUrl: tp.profile_photo || ""
                    }
                }
                // 身份证号
                else if(tp.account_type === 12) {
                    // 身份证号脱敏处理
                    let placeholder = '******************';
                    let idCardNum = tp.field1;
                    placeholder = placeholder.substr(0, idCardNum.length -8);
                    const prefix = idCardNum.substr(0, 4);
                    const suffix = idCardNum.substr(idCardNum.length-4, 4);
                    idCardNum = prefix + placeholder + suffix;
                    // 身份证号脱敏处理
                    data.retData.userInfo.idCardNum = idCardNum;
                }
            }
            return calback(null, data);
        });
        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error, null);
            return callback(error, data.retData);
        })
    };


    /**
     * 获取用户的组织信息
     *
     * @author 王俊
     * @date 2017-07-18
     *
     * @param {Object} option
     * @param {Number} option.userId
     * @param {Function} callback 回调函数
     *                      错误原因
     */
    userCenterServiceUtil.getUserOrganizationsInfo = function (option, callback) {
        (new YjxOrgRModel()).getUserOrganizationsInfo(option.userId, function (error, orgs) {
            return callback(error, orgs || []);
        });
    };

    /**
     * 获取用户的收益信息
     *
     * @author 王俊
     * @date 2017-07-18
     *
     * @param {Object} option
     * @param {Number} option.userId
     * @param {Function} callback 回调函数
     *                      error: 错误原因
     */
    userCenterServiceUtil.getUserRewardInfo = function (option, callback) {
        yjxUserUtil.getUserActivityRewardInfo__v1_7(option.userId, callback);
    };

    /**
     * 获取用户的秀米账户信息
     *
     * @author 王俊
     * @date 2017-07-18
     *
     * @param {Object} option
     * @param {Number} option.userId
     * @param {Function} callback 回调函数
     *                      error 错误原因
     */
    userCenterServiceUtil.getUserXMWalletInfo = function (option, callback) {
        yjxUserUtil.getUserPointsInfo(option.userId, callback);
    };

    /**
     * 微信用户登录(自动注册)
     *
     * @author 王俊
     * @date 2018-07-19
     *
     * @warning 此功能应由用户中心服务提供, 现考虑迁移成本, 先依赖原一键秀userUtil 实现的方法 (add by wangjun 2017-07-18)
     *
     *
     * @param {Object} option 请求参数
     * @param {Number} option.device            设备标识
     * @param {String} option.unionId           微信 unionId
     * @param {String} option.openId            微信   openId
     * @param {Number} option.accountType       微信相关的编号(如 app 微信登录: 20, xxx小程序 201)
     * @param {Object} option.wxInfo            拿到的微信信息
     * @param {Object} option.wxInfo.nickName   微信昵称
     * @param {Object} option.wxInfo.gender     微信性别
     * @param {Object} option.wxInfo.avatarUrl  微信头像
     * @param {Function} callback 回调函数
     *                      error: 失败原因
     *                      {
     *                          userId: 111
     *                      }
     */
    userCenterServiceUtil.wxLoginAndAutoRegister = function (option, callback) {
        const totalTasks =[];
        if(
            option.accountType !== 20       // 不是微信平台
            && option.accountType !== 50    // 网页微信登录
            && (option.accountType < 200 || option.accountType > 300) // 不是小程序平台
        ) {
            return callback('暂不支持的平台', null);
        }
        // 1. 使用存储过程实现微信自动登录注册, 避免并发问题
        totalTasks.push(function (callback) {
            const entity = new YjxUserModel();
            const opt = {
                unionId: option.unionId,
                openId: option.openId,
                accountType: option.accountType,
                nickName: option.wxInfo.nickName || '',
                avatarUrl: option.wxInfo.avatarUrl || ''
            };
            entity.wxLoginAndAutoReg(opt, function (error, userId) {
                if(error) return callback(error, null);
                const data = {
                    userId: userId
                };
                return callback(error, data);
            });
        });
        // 2. 完成后反向查询用户资料, 判断是否需要资源转存
        totalTasks.push(function (data, callback) {
            const entity = new YjxThirdPartyUserModel({
                user_id: data.userId,
                account_type: option.accountType,
                del_flg: 0
            });
            entity.findFromDB(function (error, thirdParts) {
                if(error || !thirdParts || thirdParts.length <=0) {
                    return callback('登录或注册失败', null);
                }
                const third = thirdParts[0];
                data.thirdEntity = third;
                // 没有头像, 无需转存
                if(!third.profile_photo || third.profile_photo.length <=0) {
                    return callback(error, data);
                }
                // 已经是oss 地址, 无需转存
                if(third.profile_photo.indexOf('http://itbour') === 0 ||
                third.profile_photo.indexOf('https://itbour') === 0) {
                    return callback(error, data);
                }

                // 需要转存头像
                data.needTransferAvatar = true;
                return callback(error, data);
            });
        });
        // 3. 按需转存头像
        totalTasks.push(function (data, callback) {
            if(!data.needTransferAvatar) {
                return callback(null, data);
            }
            const opt = {
                assetUrl: data.thirdEntity.profile_photo,
                type: 1 // 图片
            };
            assetUtil.convertAssetToOss(opt, function (error, ossUrl) {
               data.ossUrl = ossUrl;
               return callback(error, data);
            });
        });
        // 4. 按需更新头像
        totalTasks.push(function (data, callback) {
            if(!data.needTransferAvatar) {
                return callback(null, data);
            }
            const entity = new YjxThirdPartyUserModel({
                tpu_id: data.thirdEntity.tpu_id,
                profile_photo: data.ossUrl,
                update_by: data.thirdEntity.user_id
            });
            entity.updateToDB(function (error) {
                return callback(null, data);
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error, null);
            return callback(error, {userId: data.userId});
        });
    };

    /**
     * 获取用户收益明细
     *
     * @author 毛凯
     * @date 2017-07-18
     *
     * @param {Object} option 请求参数
     * @param {Number} option.device            设备标识
     * @param {Number} option.userId            用户唯一标识
     * @param {Number} option.pageNum  是否获取用户组织信息
     * @param {String} option.pageSize        是否获取用户收益信息
     * @param {Number} option.withTotalPage        是否获取用户秀米钱包信息
     * @param {Function} callback 回调函数
     *                      错误原因
     */
    userCenterServiceUtil.getUserActRewardDetail = function (option, callback) {
        const entity = new YjxActUserReward();
        entity.getUserRewardList(option.userId, option.pageNum, option.pageSize, function (err, result) {
            if (err) {
                return callback(err, null);
            }
            const data = {};
            data.list = result || [];
            if (!option.withTotalPage) {
                return callback(null, data);
            }
            entity.getUserRewardListCnt(option.userId, option.pageNum, option.pageSize, function (error, count) {
                if (error) {
                    return callback(error, null);
                }
                data.currentPage = option.pageNum;
                data.totalPage = Math.floor((count - 1) / option.pageSize) + 1;
                return callback(null, data);
            });
        });

    };



    /**
     * uc-获取用户私有码
     *
     * @author 毛凯
     * @date 2017-07-20
     *
     * @param {Object} option 请求参数
     * @param {Number} option.device            设备标识
     * @param {Number} option.userId            用户唯一标识
     * @param {Function} callback 回调函数
     *                      错误原因
     */
    userCenterServiceUtil.getUserPrivateCouponCode = function (option, callback) {
        const totalTasks = [];
        totalTasks.push(function (callback) {
            const entity = new YjxCouponModel({
                use:20,
                user_id : option.userId
            });
            entity.findFromDB(function (findCodeErr, result) {
                if (findCodeErr){
                    return callback(findCodeErr,null);
                }
                const data = {};
                if (!result || result.length <= 0){
                    return callback(null,data);
                }
                const code = result[0].c_code;
                data.code = code;
                return callback(null,data);
            });
        });
        totalTasks.push(function (data,callback) {
            if (data && data.code){
                return callback(null,data);
            }
            const code = codeUtil.genPromoCode();
            const issue_time = new Date(); // 七月 23日 2018, 4:24:11 下午;
            const expiry_time = new moment().add(2,"y");
            const new_time= new Date(expiry_time);
            const entity = new YjxCouponModel({
                c_type : 40,
                use : 20,
                c_code : code,
                state : 20,
                issue_time :issue_time,
                expiry_time:new_time,
                desc : "用户私有推广码",
                user_id :  option.userId
            });
            entity.saveToDB(function(saveErr, newId) {
                if (saveErr) {
                    return callback('新建推荐码失败', null);
                }
                data.code = code;
                return callback(null,data);
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error, null);
            return callback(error, {code : data.code});
        })
    };

    return userCenterServiceUtil;
})();

module.exports = userCenterServiceUtil;